<template>
  <div class="wardrobe-page">
    <NavigationBar />

    <!-- Breadcrumb -->
    <div class="breadcrumb">
      <div class="breadcrumb-content">
        <router-link to="/">首页</router-link>
        <span class="breadcrumb-separator">/</span>
        <span class="breadcrumb-current">我的衣橱</span>
      </div>
    </div>

    <div class="wardrobe-container">
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="category-list">
          <div
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
          >
            <!-- 展示图标 -->
            <i :class="category.icon"></i>
            <span>{{ category.name }}</span>
            <span class="category-count">{{ category.count }}</span>
          </div>
        </div>
      </div>

      <!-- 主内容区 -->
      <div class="main-content">
        <div class="toolbar" style="display: flex; gap: 10px; justify-content: space-between;">
          <div class="search-bar" style="flex: 3;">
            <a-input-search
              v-model:value="searchText"
              placeholder="搜索衣物..."
              @search="handleSearch"
            />
          </div>
          <a-button type="primary" class="upload-button custom-upload-button" @click="openUploadModal" style="flex-shrink: 1; width: auto;">
            <span class="upload-text">+ 上传衣物</span>
          </a-button>
        </div>

        <div class="clothes-grid">
          <template v-if="paginatedClothes && paginatedClothes.length > 0">
            <clothes-card
              v-for="item in paginatedClothes"
              :key="item.id"
              :item="item"
              @click="openEditModal(item)"
              @edit="openEditModal(item)"
              @delete="openDeleteModal(item)"
            />
          </template>
          <div v-else class="empty-state">
            <info-circle-outlined style="font-size: 48px; color: #94a3b8;" />
            <p>暂无衣物</p>
          </div>
        </div>

        <div class="pagination">
          <a-pagination
            v-model:current="currentPage"
            :total="totalItems"
            :page-size="pageSize"
            show-size-changer
            :page-size-options="['12', '24', '36', '48']"
            @change="handlePageChange"
            @showSizeChange="handlePageSizeChange"
          />
        </div>
      </div>
    </div>

    <!-- 上传弹窗 -->
    <a-modal
      v-model:visible="uploadModalVisible"
      title="上传衣物"
      @ok="handleUpload"
      @cancel="closeUploadModal"
    >
      <a-form :model="uploadForm" layout="vertical">
        <a-form-item label="衣物名称">
          <a-input v-model:value="uploadForm.name" placeholder="请输入衣物名称" />
        </a-form-item>
        <a-form-item label="衣物描述">
          <a-textarea v-model:value="uploadForm.description" placeholder="请输入衣物描述" :rows="4" />
        </a-form-item>
        <a-form-item label="选择分类">
          <a-select v-model:value="uploadForm.category" placeholder="请选择分类">
            <a-select-option v-for="cat in categories.filter(c => c.id !== 'all')" :key="cat.id" :value="cat.id">
              {{ cat.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="上传图片">
          <template v-if="!uploadForm.fileList.length">
            <a-upload-dragger
              v-model:fileList="uploadForm.fileList"
              :before-upload="beforeUpload"
              :max-count="1"
              :showUploadList="false"
            >
              <p class="ant-upload-drag-icon">
                <cloud-upload-outlined />
              </p>
              <p class="ant-upload-text">点击或拖拽照片到此处</p>
              <p class="ant-upload-hint">支持 JPG、PNG 格式</p>
            </a-upload-dragger>
          </template>
          <template v-else>
            <div class="preview-container">
              <img 
                :src="uploadForm.fileList[0].url" 
                class="preview-image"
                alt="预览图片"
              />
              <a-button type="link" @click="uploadForm.fileList = []" class="change-image">
                更换图片
              </a-button>
            </div>
          </template>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑衣物"
      @ok="handleEdit"
      @cancel="closeEditModal"
    >
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="衣物名称">
          <a-input v-model:value="editForm.name" placeholder="请输入衣物名称" />
        </a-form-item>
        <a-form-item label="衣物描述">
          <a-textarea v-model:value="editForm.description" placeholder="请输入衣物描述" :rows="4" />
        </a-form-item>
        <a-form-item label="选择分类">
          <a-select v-model:value="editForm.category" placeholder="请选择分类">
            <a-select-option v-for="cat in categories.filter(c => c.id !== 'all')" :key="cat.id" :value="cat.id">
              {{ cat.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="当前图片">
          <img :src="editForm.currentImage" class="preview-image" alt="当前图片">
        </a-form-item>
        <a-form-item label="更换图片（可选）">
          <a-upload-dragger
            v-model:fileList="editForm.fileList"
            :before-upload="beforeUpload"
            :max-count="1"
          >
            <p class="ant-upload-drag-icon">
              <cloud-upload-outlined />
            </p>
            <p class="ant-upload-text">点击或拖拽照片到此处</p>
            <p class="ant-upload-hint">支持 JPG、PNG 格式</p>
          </a-upload-dragger>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除确认弹窗 -->
    <a-modal
      v-model:visible="deleteModalVisible"
      title="删除确认"
      @ok="handleDelete"
      @cancel="closeDeleteModal"
    >
      <p>确定要删除这件衣物吗？此操作不可撤销。</p>
    </a-modal>

    <PageFooter />
  </div>
</template>

<script>
import {defineComponent, ref, computed, onMounted, watch} from 'vue'
import { message } from 'ant-design-vue'
import NavigationBar from '@/components/layout/NavigationBar.vue'
import PageFooter from '@/components/layout/PageFooter.vue'
import '@/assets/styles/wardrobe.css'
import ClothesCard from '@/components/ClothesCard.vue'
import {
  CloudUploadOutlined,
  InfoCircleOutlined
} from '@ant-design/icons-vue'
import axios from "axios"
import { useRouter } from 'vue-router'

export default defineComponent({
  name: 'WardrobePage',
  components: {
    NavigationBar,
    PageFooter,
    ClothesCard,
    CloudUploadOutlined,
    InfoCircleOutlined
  },
  setup() {
    const router = useRouter()
    // 状态管理
    const searchText = ref('')
    const selectedCategory = ref('all')
    const currentPage = ref(1)
    const pageSize = ref(12)
    const uploadModalVisible = ref(false)
    const editModalVisible = ref(false)
    const deleteModalVisible = ref(false)
    const currentEditItem = ref(null)
    const currentDeleteItem = ref(null)

    // 表单数据
    const uploadForm = ref({
      name: '',
      description: '',
      category: '',
      fileList: []
    })

    const editForm = ref({
      name: '',
      description: '',
      category: '',
      currentImage: '',
      fileList: []
    })

    // 模拟数据
    const categories = ref([
      { id: 'all', name: '全部衣物', icon: 'fas fa-th-large', count: 0 },
      { id: 'top', name: '上衣', icon: 'fas fa-tshirt', count: 0 },
      { id: 'dress', name: '裙装', icon: 'fas fa-female', count: 0 },
      { id: 'pants', name: '裤装', icon: 'fas fa-shopping-bag', count: 0 },
      { id: 'coat', name: '外套', icon: 'fas fa-tshirt', count: 0 },
      { id: 'shoes', name: '鞋子', icon: 'fas fa-shoe-prints', count: 0 },
      { id: 'watch', name: '手表', icon: 'fas fa-clock', count: 0 },
      { id: 'accessories', name: '装饰', icon: 'fas fa-gift', count: 0 }
    ])

    const clothesItems = ref([])

    // 计算属性
    const filteredClothes = computed(() => {
      // 创建分类ID映射
      const categoryMap = {
        'top': 1,
        'dress': 2,
        'pants': 3,
        'coat': 4,
        'shoes': 5,
        'watch': 6,
        'accessories': 7
      }
      
      return clothesItems.value.filter(item => {
        const matchesCategory = selectedCategory.value === 'all' ||
          item.categoryId === categoryMap[selectedCategory.value]
        const matchesSearch = !searchText.value ||
          item.name.toLowerCase().includes(searchText.value.toLowerCase())
        return matchesCategory && matchesSearch
      })
    })

    const paginatedClothes = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredClothes.value.slice(start, end)
    })

    const totalItems = computed(() => filteredClothes.value.length)

    // 方法
    const selectCategory = (categoryId) => {
      selectedCategory.value = categoryId
      currentPage.value = 1
    }

    const handleSearch = (value) => {
      searchText.value = value
      currentPage.value = 1
    }

    const handlePageChange = (page) => {
      currentPage.value = page
    }

    const handlePageSizeChange = (current, size) => {
      pageSize.value = size
      currentPage.value = 1
    }

    const beforeUpload = (file) => {
      // 校验文件类型
      const isValidType = ['image/jpeg', 'image/png'].includes(file.type);
      if (!isValidType) {
        message.error('只能上传 JPG/PNG 格式的图片！');
        return false;
      }

      // 校验文件大小
      const isLt5M = file.size / 1024 / 1024 < 10;
      if (!isLt5M) {
        message.error('图片大小不能超过 10MB！');
        return false;
      }

      // 创建对象URL用于预览
      file.url = URL.createObjectURL(file);
      
      return false; // 返回false以手动处理上传
    };

    const openUploadModal = () => {
      uploadModalVisible.value = true
    }

    const closeUploadModal = () => {
      uploadModalVisible.value = false
      uploadForm.value = {
        name: '',
        description: '',
        category: '',
        fileList: []
      }
    }

    const updateCategoryCounts = () => {
      // 重置所有分类的计数
      categories.value.forEach(category => {
        category.count = 0
      })

      // 统计每个分类的数量
      clothesItems.value.forEach(item => {
        // 直接使用 categoryId 进行映射
        const categoryMap = {
          '1': 'top',
          '2': 'dress',
          '3': 'pants',
          '4': 'coat',
          '5': 'shoes',
          '6': 'watch',
          '7': 'accessories'
        }
        
        const categoryId = item.categoryId?.toString()
        if (categoryId && categoryMap[categoryId]) {
          const category = categories.value.find(c => c.id === categoryMap[categoryId])
          if (category) {
            category.count++
          }
        }
      })

      // 更新"全部"分类的数量
      const allCategory = categories.value.find(c => c.id === 'all')
      if (allCategory) {
        allCategory.count = clothesItems.value.length
      }

      console.log('Updated category counts:', categories.value) // 添加日志
    }

    // 监听 clothesItems 的变化
    watch(clothesItems, () => {
      updateCategoryCounts()
    }, { immediate: true })

    const fetchClothesList = async () => {
      try {
        const userId = localStorage.getItem('userId')
        const token = localStorage.getItem('token')
        
        if (!userId) {
          console.error('No userId found in localStorage')
          message.error('用户ID不存在，请重新登录')
          router.push('/login')
          return
        }
        
        if (!token) {
          console.error('No token found in localStorage')
          message.error('登录凭证不存在，请重新登录')
          router.push('/login')
          return
        }

        console.log('开始获取衣物列表...')
        console.log('请求参数:', {
          userId: userId,
          token: token.substring(0, 10) + '...' // 只显示token的前10位
        })

        const response = await axios.get(`/api/clothes/users/${userId}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          }
        })

        console.log('衣物列表响应:', response)

        if (response.data.success) {
          clothesItems.value = response.data.data.map(item => ({
            id: item.clothesId,
            name: item.name,
            categoryId: item.categoryId,
            date: item.createdAt,
            image: `/api/images/${item.imageUrl.split('/').pop()}`,
            description: item.description || ''
          }))
          
          // 更新分类计数
          updateCategoryCounts()
        } else {
          message.error(response.data.errorMsg || '获取衣物列表失败')
        }
      } catch (error) {
        console.error('获取衣物列表失败:', error)
        console.error('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status,
          config: {
            url: error.config?.url,
            method: error.config?.method,
            headers: error.config?.headers
          }
        })
        
        if (error.response) {
          if (error.response.status === 401) {
            message.error('登录已过期，请重新登录')
            router.push('/login')
          } else if (error.response.status === 400) {
            message.error(error.response.data.message || '请求参数错误')
          } else {
            message.error('获取衣物列表失败，请重试')
          }
        } else {
          message.error('网络错误，请检查网络连接')
        }
      }
    }

    const handleUpload = async () => {
      if (!uploadForm.value.name) {
        message.warning('请输入衣物名称')
        return
      }
      if (!uploadForm.value.category) {
        message.warning('请选择衣物类别')
        return
      }
      if (uploadForm.value.fileList.length === 0) {
        message.warning('请上传衣物照片')
        return
      }

      try {
        const file = uploadForm.value.fileList[0]
        const formData = new FormData()
        
        // 添加文本字段
        formData.append('name', uploadForm.value.name)
        formData.append('description', uploadForm.value.description || uploadForm.value.name)
        
        // 转换分类ID为数字
        const categoryMap = {
          'top': 1,
          'dress': 2,
          'pants': 3,
          'coat': 4,
          'shoes': 5,
          'watch': 6,
          'accessories': 7
        }
        const categoryId = categoryMap[uploadForm.value.category]
        if (!categoryId) {
          message.error('无效的分类')
          return
        }
        formData.append('categoryId', categoryId.toString())
        
        // 添加用户ID
        const userId = localStorage.getItem('userId')
        if (!userId) {
          message.error('用户ID不存在')
          return
        }
        formData.append('userId', userId)
        
        // 添加图片文件
        formData.append('image', file.originFileObj || file)
        
        console.log('Uploading with form data:', {
          name: uploadForm.value.name,
          description: uploadForm.value.description,
          categoryId: categoryId,
          userId: userId,
          image: file.name
        })
        
        // 上传图片和创建衣物记录
        const response = await axios.post('/api/clothes/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })

        if (response.data.success) {
          message.success('上传成功')
          closeUploadModal()
          fetchClothesList()
        } else {
          message.error(response.data.errorMsg || '上传失败')
        }
      } catch (error) {
        console.error('Upload error:', error)
        if (error.response) {
          console.error('Error response:', error.response.data)
          message.error(error.response.data.errorMsg || '上传失败，请重试')
        } else {
          message.error('上传失败，请重试')
        }
      }
    }

    const openEditModal = (item) => {
      currentEditItem.value = item
      // 找到对应的分类
      const categoryMap = {
        '1': 'top',
        '2': 'dress',
        '3': 'pants',
        '4': 'coat',
        '5': 'shoes',
        '6': 'watch',
        '7': 'accessories'
      }
      
      // 获取当前衣物的分类ID对应的分类名称
      const categoryId = item.categoryId?.toString()
      const currentCategory = categoryMap[categoryId]
      
      editForm.value = {
        name: item.name,
        description: item.description || '',
        category: currentCategory || '',
        currentImage: item.image,
        fileList: []
      }
      editModalVisible.value = true
    }

    const closeEditModal = () => {
      editModalVisible.value = false
      currentEditItem.value = null
      editForm.value = {
        name: '',
        description: '',
        category: '',
        currentImage: '',
        fileList: []
      }
    }

    const handleEdit = async () => {
      if (!editForm.value.name || !editForm.value.category) {
        message.error('请填写完整信息！')
        return
      }

      const formData = new FormData()
      formData.append('name', editForm.value.name)
      formData.append('description', editForm.value.description || editForm.value.name)
      
      // 转换分类ID为数字
      const categoryMap = {
        'top': 1,
        'dress': 2,
        'pants': 3,
        'coat': 4,
        'shoes': 5,
        'watch': 6,
        'accessories': 7
      }
      const categoryId = categoryMap[editForm.value.category]
      if (!categoryId) {
        message.error('无效的分类')
        return
      }
      formData.append('categoryId', categoryId.toString())

      // 如果有新图片，添加图片文件
      if (editForm.value.fileList.length > 0) {
        formData.append('image', editForm.value.fileList[0].originFileObj || editForm.value.fileList[0])
      }

      const token = localStorage.getItem('token')
      const response = await axios.put(`/api/clothes/upload/${currentEditItem.value.id}`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.data.success) {
        message.success('修改成功')
        closeEditModal()
        fetchClothesList()
      } else {
        message.error(response.data.errorMsg || '修改失败')
      }
    }

    const openDeleteModal = (item) => {
      currentDeleteItem.value = item
      deleteModalVisible.value = true
    }

    const closeDeleteModal = () => {
      deleteModalVisible.value = false
      currentDeleteItem.value = null
    }

    const handleDelete = async () => {
      try {
        if (!currentDeleteItem.value) return

        const token = localStorage.getItem('token')
        const response = await axios.delete(`/api/clothes/${currentDeleteItem.value.id}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        })

        if (response.data.success) {
          message.success('删除成功')
          closeDeleteModal()
          fetchClothesList()
        } else {
          message.error(response.data.errorMsg || '删除失败')
        }
      } catch (error) {
        console.error('Delete error:', error)
        message.error('删除失败，请重试')
      }
    }

    // 在组件挂载时调用
    onMounted(() => {
      fetchClothesList()
    })

    return {
      searchText,
      selectedCategory,
      currentPage,
      pageSize,
      uploadModalVisible,
      editModalVisible,
      deleteModalVisible,
      uploadForm,
      editForm,
      categories,
      clothesItems,
      filteredClothes,
      paginatedClothes,
      totalItems,
      selectCategory,
      handleSearch,
      handlePageChange,
      handlePageSizeChange,
      beforeUpload,
      openUploadModal,
      closeUploadModal,
      handleUpload,
      openEditModal,
      closeEditModal,
      handleEdit,
      openDeleteModal,
      closeDeleteModal,
      handleDelete
    }
  }
})
</script>

<style scoped>
.preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  object-fit: contain;
  border-radius: 8px;
}

.change-image {
  color: #0ea5e9;
}

.clothes-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  padding: 1rem 0;
}

.clothes-grid > * {
  width: calc(25% - 0.75rem);
}

@media (max-width: 1024px) {
  .clothes-grid > * {
    width: calc(33.333% - 0.666rem);
  }
}

@media (max-width: 768px) {
  .clothes-grid > * {
    width: calc(50% - 0.5rem);
  }
}

@media (max-width: 480px) {
  .clothes-grid > * {
    width: calc(50% - 0.5rem);
  }
}
</style>
